var express = require('express');
var async = require('async');

var utils = require('../functions/utils');
var router = express.Router();

router.post('/', function(req,res)
{
/*
	Input parameters 
	 *		register  '0':login , '1':register	
	 *		loginId
	 *  	loginPwd
*/
	var register = req.body.register;	utils.checkParamValue('register' , register);
	var loginId = req.body.loginId;		utils.checkParamValue('loginId' , loginId);
	var loginPwd = req.body.loginPwd;	utils.checkParamValue('loginPwd' , loginPwd);

	// session id 없으니 loginId로 대신한다. 
	req.body.sessionId = loginId;
	utils.callLog(req);

	// 금지어 체크
	utils.checkProhibitedWord(loginId);

	if(global.config.debug)
	{
		if(register == '0')
		    utils.debug(req.originalUrl + ' : login');
		else
			utils.debug(req.originalUrl + ' : register');
	}

	// email check
	if(!utils.emailCheck(loginId))
	{
		var err = new Error('Invalid email address : ' + loginId);
		err.code = '524';
		throw err;
	}

	var _list = loginId.split("@");

	var userName = _list[0];
	var domain = _list[1];
	var userKey = null;

	// 패스워드 암호화한다. 
	loginPwd = utils.passwordEncrypt(loginPwd);

//////////////////////////////////////////////////////////////////////////////////

		// mail domain check 후 sp call 
		async.waterfall([
			function(cb)
			{
				// 가입 시 
				if(register == '1')
				{
					// lookup가져오는데 시간이 오래걸리는 domain은 미리 밴다 - 이유는 모르겠음.
					if(domain.toLowerCase() == 'gemail.com')
					{
						utils.setSendMmailInfo(loginId,null);
						utils.errorLog(req , '699' , 'invalid domain : ' + domain);
						cb(null , false);
					}
					else
					{
						var dns = require ('dns');
						dns.resolveMx( domain, function (err, addresses) // mx lookup 해서 
						{
							var validDomain = false;
							// 결과가 있고 exchage server 가 존재할 경우만 true
							if (!err)
							{
								for(var i = 0 ; i < addresses.length ; i ++)
								{
									if(addresses[i].exchange.length > 0)
									{
										validDomain = true;
										break;
									}

								}
							}

							// 없는 dns일 경우는 invalid로 마킹. 
							if (!validDomain)
							{
								utils.setSendMmailInfo(loginId,null);
								utils.errorLog(req , '699' , 'invalid domain : ' + domain);
							}

							cb(null , validDomain);

						}); //dns.resolve4
					}// else gemail 
				}
				// 로긴 시 
				else
				{
					cb(null , true);
				}
			},
			function(validDomain , cb)
			{
				//  insert , update : master
				global.master_db.connection.getConnection(function(err,connection)
				{
					if(err)
					{
						throw err;
					}

					var input_param = [register, loginId , loginPwd, userName, validDomain];

					var sql = 'call api_loginWithEmail(? , ? , ? ,? , ? , @key, @result); SELECT @key as userKey , @result AS result';
					var query = connection.query(sql, input_param , function (err, rows) 
					{
						connection.release();
						if(err)
						{
							throw err;
						}

						var ret = { 'body' : {} };	 // 기본값은 성공

						switch(rows[1][0].result)
						{
							case 200:
							case 201:
							case 202:
								ret.code=rows[1][0].result;
								ret.body.userKey=rows[1][0].userKey;
								userKey = rows[1][0].userKey;
								break;
							case 520:
								var err = new Error('Email is in use : ' + loginId);
								err.code = '520';
								throw err;
								break;
							case 522:
								var err = new Error('Unregistered email : ' + loginId);
								err.code = '522';
								throw err;
								break;

							case 524:
								var err = new Error('Email and Pwd mismatch : ' + loginId + ',' + loginPwd);
								err.code = '524';
								throw err;
								break;
							default:
								throw new Error();

						}

						res.json(ret);
						res.end();

					}); // call api_loginWithEmail

				}); // getConnection
			}
		]); // waterfall

//////////////////////////////////////////////////////////////////////////////////


	
});

module.exports = router;